<?php
@include("connect.php");

// 购物车的逻辑
//   判断该商品是否已经存在
//         存在   num+1
//         不存在  插入


$username = $_POST['username'];
$id = $_POST['goods_id'];
$num = $_POST['num'];
// $goodsPrice = $_POST['goods_price'];
// var_dump($username);
// var_dump($id);
// var_dump($num);
// var_dump($goodsPrice);

// $username = '55';
// $id = '99';
// $num = 5;
// $goodsPrice = '999';


$obj = [];

if ($username && $id && $num) {
    // 判断购物车中yy是否买了该商品

    $sql = "select * from cart where goods_id = $id and username = '$username'";
    $res = mysqli_query($conn, $sql);
    $arr = mysqli_fetch_array($res);
    if ($arr) {
        // 如果已经找到了  就修改数量
        $sql = "UPDATE cart set num = num + $num where username = '$username' and goods_id = '$id'";
        mysqli_query($conn, $sql);
        // 受影响的行数
        $rows = mysqli_affected_rows($conn);
        if ($rows > 0) {
            $obj['status'] = true;
            $obj['msg'] = '数量修改成功';
        } else {
            $obj['status'] = false;
            $obj['msg'] = '服务器错误1';
        }
    } else {
        // 如果没有找到  就插入数据
        // $sql = "insert into cart (id,username,num,price) values ('$id','$username', '$num','$goodsPrice')";
        $sql = "insert into cart (goods_id,username,num) values ('$id','$username' ,'$num')";


        mysqli_query($conn, $sql);
        // 受影响的行数
        $rows = mysqli_affected_rows($conn);
        if ($rows > 0) {
            $obj['status'] = true;
            $obj['msg'] = '成功加入购物车';
        } else {
            $obj['status'] = false;
            $obj['msg'] = '服务器错误22';
        }
    }
} else {
    $obj['status'] = false;
    $obj['msg'] = '前端数据有误';
}

// 返回给前端的数据  --- json格式的字符串
echo (json_encode($obj, JSON_UNESCAPED_UNICODE));
